#region Using

using System;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using System.Web.Caching;
using BlogEngine.Core;
using BlogEngine.Core.Provider;
using BlogEngine.Core.Provider.Interfaces;

#endregion

namespace BlogEngine.Core.Provider.XML
{
	/// <summary>
	/// Implementation of BlogProvider
	/// </summary>
	public class CIExtensionSettings : IExtensionSettings
	{
		private static string _fileName = Provider.Folder + "extensions.xml";

		/// <summary>
		/// Loads the settings from the provider.
		/// </summary>
		/// <returns></returns>
		public List<ManagedExtension> Load()
		{
			// check cache first
			List<ManagedExtension> settings = (List<ManagedExtension>) HttpContext.Current.Cache["Extensions"];

			if (settings != null)
				return settings;

			if (!File.Exists(_fileName))
				return null;

			using (TextReader reader = new StreamReader(_fileName))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(List<ManagedExtension>));
				settings = (List<ManagedExtension>)serializer.Deserialize(reader);

				HttpContext.Current.Cache["Extensions"] = settings;

				return settings;
			}
		}

		/// <summary>
		/// Saves the settings to the provider.
		/// </summary>
		/// <param name="settings"></param>
		public void Save(List<ManagedExtension> settings)
		{
			if (settings == null)
				throw new ArgumentNullException("settings");

			using (TextWriter writer = new StreamWriter(_fileName))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(List<ManagedExtension>));
				serializer.Serialize(writer, settings);
			}

			HttpContext.Current.Cache["Extensions"] = settings;
		}
	}
}
